package org.example.liuy.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.lang.reflect.Method;

public class ControllerMethodHandler implements HttpHandler {
    private final Object controllerInstance;
    private final Method method;

    public ControllerMethodHandler(Object controllerInstance, Method method) {
        this.controllerInstance = controllerInstance;
        this.method = method;
        this.method.setAccessible(true);
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        try {
            // 这里应该实现参数解析、方法调用等逻辑
            Object result = method.invoke(controllerInstance, exchange);
            // 处理返回结果
            handleResult(exchange, result);
        } catch (Exception e) {
            throw new IOException("Error handling request", e);
        }
    }

    private void handleResult(HttpExchange exchange, Object result) throws IOException {
        // 处理控制器方法的返回结果
        if (result instanceof String) {
            byte[] response = ((String) result).getBytes();
            exchange.sendResponseHeaders(200, response.length);
            exchange.getResponseBody().write(response);
        } else {
            exchange.sendResponseHeaders(200, 0);
        }
        exchange.getResponseBody().close();
    }
}
